import jwt
from functools import wraps
from flask import request, g
from jwt import exceptions
from app.extensions import json_response


def login_require(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            token = request.headers["Authorization"].split()[1]
            payload = jwt.decode(token, "1qaz2wsx3edc", algorithms=["HS256"])
        except exceptions.ExpiredSignatureError:
            return json_response(code=401, data={"msg": "登录过期，请重新登录"})
        except exceptions.DecodeError:
            return json_response(code=401, data={"msg": "鉴权失败"})
        except exceptions.InvalidTokenError:
            return json_response(code=401, data={"msg": "鉴权失败，无效token"})

        user_info = payload.get("sub")
        g.user_id = user_info.get("user_id")
        g.user_name = user_info.get("user_name")
        return func(*args, **kwargs)

    return wrapper

